package servlet;

import java.io.IOException;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.Map.Entry;
import java.util.Set;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;

import dao.book.imp.BookDaoImp;
import pojo.Book;

/**
 * Servlet implementation class ShoppingCartServlet
 */
public class ShoppingCartServlet extends HttpServlet {
	private static final long serialVersionUID = 1L;
	public static Map<Book, Integer> bookmap = new HashMap<Book,Integer>();
       
    /**
     * @see HttpServlet#HttpServlet()
     */
    public ShoppingCartServlet() {
        super();
        List<Book> books = new BookDaoImp().findAll();
        for(Book book:books){
        	bookmap.put(book, 0);
        }
    }

	/**
	 * @see HttpServlet#doGet(HttpServletRequest request, HttpServletResponse response)
	 */
	protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
		HttpSession sen = request.getSession();
		String bookId = request.getParameter("bid");
		String uname = request.getParameter("username");
		//Book book = new BookDaoImp().findOne(bookId);
		if(true){
			Map<Book, Integer> bookmap1 = new HashMap<Book,Integer>();
			for (Map.Entry<Book, Integer> entry : bookmap.entrySet()) {
				   if(bookId.equals(entry.getKey().getId())){
					   entry.setValue(entry.getValue()+1);
				   }
				   if(entry.getValue()!=0){
					   bookmap1.put(entry.getKey(), entry.getValue());
				   }
			}
			Set<Entry<Book, Integer>> set = bookmap1.entrySet();
			sen.setAttribute("uname", uname);
			sen.setAttribute("bookset", set);
			sen.setAttribute("prompt", null);
			response.sendRedirect("../shoppingcart.jsp");
		}
	}

	/**
	 * @see HttpServlet#doPost(HttpServletRequest request, HttpServletResponse response)
	 */
	protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
		// TODO Auto-generated method stub
		doGet(request, response);
	}

}
